<template>
  <div :class="inputStyle == 'notBorder' ? 'not-border' : 'default-border'">
    <div :class="['input-box',focusStatus == 'focus' ? 'input-box-focus' : focusStatus == 'error' ? 'input-box-error' : '', disabled ? 'input-disabled' : '']">
      <input ref="gzInput"
      :type="type"
      :class="['gz-input']"
      :style="customStyle"
      v-model="modelValue"
      :placeholder="placeholder"
      :disabled="disabled"
      :autofocus="focus"
      :readonly="readonly"
      @input="input(modelValue)"
      @focus="handleFocus"
      @blur="handleBlur(modelValue)" />
      <slot name="suffix"></slot>
    </div>
    <div class="valid-error" v-if="error">{{error}}</div>
  </div>
</template>

<script>
  import formValidator from '@/service/form/formActiveValidate'
  export default {
    name: 'gzInput',
    /**
     * type: 输入类型
     * value: 绑定的value值
     * validate: {Object} 验证规则（参考 @/service/form/formValidator中的rules）
     * desc: 说明(非title)
     * placeholder: 空占位提示
     * disabled: 是否可输入
     * focus: 是否默认选中
     * customStyle: {Object} 自定义input Style样式
     * readonly: 是否只读
     * inputStyle: 组件风格，(notBorder 无边框)
     */
    props: ['type','value','validate','placeholder','disabled','focus','customStyle','readonly','inputStyle'],
    model: {
      prop: 'value',
      event: 'valueChange'
    },
    data() {
      return {
        modelValue: this.value ? this.value : '',
        error: '',
        focusStatus: 'default',
        abValidate: {}
      }
    },
    mounted() {
      let directives = this.$vnode.data.directives ? this.$vnode.data.directives : []
      if(directives.length > 0) {
        let that = this
        directives.forEach((v) => {
          if(v.name == 'ab-validate') {
            that.abValidate = v.value
          }
        })
      }
    },
    methods: {
      input(e) {
        this.$emit('valueChange',e)
      },

      handleFocus(e) {
        this.error = ''
        this.focusStatus = 'focus'
      },

      handleBlur(e) {
        let validate = this.validate ? this.validate : this.abValidate
        formValidator.activeValidate(e,validate).then(res => {
          this.error = ''
          this.focusStatus = 'default'
        }).catch(err => {
          this.error = err
          this.focusStatus = 'error'
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .weui-cell__bd .ab-invalid {
    border: 0px;
  }
</style>
